package cn.adelyn.base.rbac.feign;

import cn.adelyn.base.api.rbac.feign.PermissionFeignClient;
import cn.adelyn.base.api.rbac.pojo.bo.CheckPermissionBO;
import cn.adelyn.base.rbac.service.MenuPermissionService;
import cn.adelyn.common.core.response.ResponseEnum;
import cn.adelyn.common.core.response.ServerResponseEntity;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**  
 * @author chengze
 * @date 2022/12/12
 * @desc 权限校验
 */
@RestController
public class PermissionFeignController implements PermissionFeignClient {

	@Autowired
	private MenuPermissionService menuPermissionService;

	// 如果一个用户有多个角色怎么办？
	// 本项目没有这种场景，高权限可以向下覆盖，如果通过 userId 到 auth 查 userTypes 会增加一次网络IO，不做处理
	@Override
	public ServerResponseEntity<Boolean> checkPermission(CheckPermissionBO checkPermissionBO) {

		// 目前该用户拥有的permission
		List<String> userPermissions = menuPermissionService.listUserPermissions(checkPermissionBO.getUserType());

		// 查询uri需要的permission
		String uriPermission = menuPermissionService.getUriPermission(checkPermissionBO.getUri(), checkPermissionBO.getMethod());

		// 如果uri 没有匹配到，则说明uri不需要权限，直接校验成功
		if (StrUtil.isEmpty(uriPermission)){
			return ServerResponseEntity.success();
		}

		// 匹配到uri,且有permission，通过
		if (userPermissions.contains(uriPermission)){
			return ServerResponseEntity.success();
		}

		return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);

	}

}
